package com.dao.zk;

import com.bean.zk.Log;
import com.util.zk.Dbutil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.springframework.stereotype.Repository;

import java.sql.Connection;
import java.util.List;
import java.util.Map;

@Repository
public class LogDAO {



    /**
     * 查询所有的日志
     *
     * @return
     */
    public List<Log> getAllLogs() {

        Connection con = null;
        QueryRunner query = new QueryRunner();
        List<Log> log = null;
        try {
            con = Dbutil.getConnection();
            String sql = "select * from log";
            log = query.query(con, sql, new BeanListHandler<>(Log.class));
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            Dbutil.closeAll(null,null,con);
        }
        return log;
    }

    /**
     * 根据lid查询日志
     * @param lid
     * @return
     */
    public Log selLogByLid(Integer lid) {
        Connection con = null;
        QueryRunner query = new QueryRunner();
        Log log = null;
        try {
            con = Dbutil.getConnection();
            String sql = "select * from log where lid = ?";
            log = query.query(con, sql, new BeanHandler<>(Log.class), lid);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            Dbutil.closeAll(null,null,con);
        }
        return log;
    }

    /**
     * 添加日志
     *
     * @return
     */
    public int insert(Log log) {
        Connection con = null;
        QueryRunner query = new QueryRunner();
        int update = 0;
        try {
            con = Dbutil.getConnection();
            String sql = "insert into log values(null,?,?,now(),?,?,?)";
            Object[] args = new Object[]{log.getRemark(), log.getEid(), log.getBefore(), log.getAfter(), log.getLtype()};
            update = query.update(con, sql, args);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            Dbutil.closeAll(null, null, con);
        }
        return update;
    }

    /**
     * 删除一条日志
     * @param lid 日志id
     * @return
     */
    public int delete( int lid) {
        Connection con = null;
        QueryRunner query = new QueryRunner();
        int delete = 0;
        try {
            con = Dbutil.getConnection();
            String sql = "delete from log where lid = ?";
            delete = query.update(con, sql, lid);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            Dbutil.closeAll(null, null, con);
        }
        return delete;
    }

}
